package demo;

import com.xnx3.StringUtil;
import com.xnx3.microsoft.*;
import com.xnx3.microsoft.Window;
import com.xnx3.robot.Robot;
import com.xnx3.robot.support.CoordBean;

import javax.swing.*;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;

/**
 * mhxy实例
 */
public class MhxyDemo extends JFrame {

	private JPanel contentPane;
	private JTextArea textArea;
	private Com com;
	private Window window;
	private Robot robot;
	private FindStr findStr;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					MhxyDemo frame = new MhxyDemo();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public MhxyDemo() {
		com=new Com();
		window = new Window(com.getActiveXComponent());
        findStr = new FindStr(com.getActiveXComponent());
		//返回创建Com()的结果，如果自检过程中发现异常，创建Com失败，则调用此会返回false
		if(!com.isCreateSuccess()){
			return;
		}
		robot = new Robot();
		robot.setSourcePath(MhxyDemo.class);

		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 600, 450, 400);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		
		JButton button = new JButton("获取窗口");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				getMhxyWindow();
			}
		});

		JButton btnNewButton = new JButton("开始抓鬼");
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				startzhuagui();
			}
		});

		textArea = new JTextArea();
		textArea.setLineWrap(true);
		
		JButton btnNewButton_1 = new JButton("测试使用");
		btnNewButton_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				imageSearchAndMouseRightClick();

			}
		});
		GroupLayout gl_contentPane = new GroupLayout(contentPane);
		gl_contentPane.setHorizontalGroup(
			gl_contentPane.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPane.createSequentialGroup()
					.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
						.addComponent(btnNewButton_1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
						.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING, false)
							.addComponent(button, GroupLayout.DEFAULT_SIZE, 186, Short.MAX_VALUE)
							.addComponent(btnNewButton, GroupLayout.DEFAULT_SIZE, 186, Short.MAX_VALUE)))
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(textArea, GroupLayout.DEFAULT_SIZE, 242, Short.MAX_VALUE)
					.addContainerGap())
		);
		gl_contentPane.setVerticalGroup(
			gl_contentPane.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_contentPane.createSequentialGroup()
					.addComponent(button, GroupLayout.PREFERRED_SIZE, 46, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(btnNewButton, GroupLayout.PREFERRED_SIZE, 51, GroupLayout.PREFERRED_SIZE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(btnNewButton_1)
					.addGap(103))
				.addGroup(gl_contentPane.createSequentialGroup()
					.addComponent(textArea, GroupLayout.DEFAULT_SIZE, 262, Short.MAX_VALUE)
					.addContainerGap())
		);
		contentPane.setLayout(gl_contentPane);
	}
	public JTextArea getTextArea() {
		return textArea;
	}
	
	public void getMhxyWindow(){
		String allWindowsStr = window.enumWindow(0,"梦幻西游","",1);
		if(StringUtil.isNotEmpty(allWindowsStr)){
			String[] windowarr = allWindowsStr.split(",");
			movewindow(windowarr);

		}
	}


	//创建输出日志的窗口
	public void createWindowViewLog(int hwnd,int i,String title){
		JLabel userLabel = new JLabel(title+":");
		userLabel.setBounds(10,50*i+200,80,25);
		contentPane.add(userLabel);

		JTextField userText = new JTextField(20);
		userText.setBounds(10,50*i+200+25,165,25);
		userText.disable();
		userText.setText("等待启动");
		contentPane.add(userText);
	}

	/*
	 * 自动排列窗口
	 */
	public void movewindow(String[] windowarr){
		int windowx = 0;
		int windowy = 0;
		for (int i = 0; i < windowarr.length; i++) {
			String s = windowarr[i];
			int hwnd = Integer.valueOf(s);
			createWindowViewLog(hwnd,i,window.getWindowTitle(hwnd));
			//addLog("找到窗口:"+window.getWindowTitle(hwnd));
			window.moveWindow(hwnd,windowx,windowy);
			addLog("移动窗口到:("+windowx+","+windowy+")");

			//确定下一个窗口的坐标
			int[] hwndrect= window.getWindowRect(hwnd);
			if(hwndrect[3] > 1980){
				windowx = 0;
				windowy = hwndrect[4];
				window.moveWindow(hwnd,windowx,windowy);
				addLog("移动窗口到:("+windowx+","+windowy+")");
				hwndrect= window.getWindowRect(hwnd);
				windowx = hwndrect[3];
				windowy = hwndrect[2];
			}else{
				windowx = hwndrect[3];
				windowy = hwndrect[2];
			}
		}
	}
	

	/**
	 * 两个在本地的图片对比
	 */
	public void imageSearchBySource(){
		Robot robot = new Robot();
		robot.setSourcePath(MhxyDemo.class);
		List<CoordBean> list = robot.imageSearch(robot.getResourceImage("source.png"), robot.getResourceImage("search.png"), Robot.SIM_ACCURATE);
		addLog("imageSearchBySource搜索到了"+list.size()+"个图片");
		for (int i = 0; i < list.size(); i++) {
			CoordBean coord = list.get(i);
			addLog("第"+(i+1)+"个图片坐标："+coord.getX()+","+coord.getY());
		}
	}
	
	/**
	 * 开始抓鬼
	 */
	public void startzhuagui(){



		//查找当前运行的程序中标题包含“寻仙 -”三个字的窗口句柄，
		int hwnd=window.findWindow(0, null, "44584070");

		//获取队长窗口
		if(hwnd>0){
			/*
			 * 对找到的寻仙这个窗口进行绑定，绑定完毕后，那么所有的鼠标、键盘、图色等操作就是都是对这个窗口（寻仙游戏）操作的，完全后台的~~，窗口可以被遮挡、点击葫芦隐藏，但是不可以最小化
			 * 寻仙的就是这种模式绑定，只需要传入窗口句柄就可
			 * 其他游戏的请自行组合测试绑定模式,使用： com.bind(hwnd, display, mouse, key, mode) 自行测试
			 */
			if(com.bind(hwnd,"normal","normal","windows",1)){
				/**
				 * 绑定完毕，对游戏的操作全在这里
				 */
				Press press=new Press(com.getActiveXComponent());	//创建模拟按键对象
				Mouse mouse=new Mouse(com.getActiveXComponent());	//创建模拟鼠标对象
				Sleep sleep=new Sleep();							//创建延迟等待对象

				window.setWindowActivate(hwnd);//激活这个窗口
				int[] hwndrect= window.getWindowRect(hwnd);//当前窗口区域坐标
				//打开包裹
				if(openBag(robot,press,hwndrect)){
					//mouse.mouseMoveTo(214,467);
					mouse.mouseRealMove(99,680,1,1,hwndrect);
					//飞驿站
					if(fly77(0,0,2,hwndrect,mouse,sleep)){
						sleep.sleep(100);
						hideAll(press);
                        //找驿站老板并点击
					}
					/*//找到红色合成棋
					List<CoordBean> list = robot.imageSearch(hwndrect[1], hwndrect[2], hwndrect[3], hwndrect[4], "qz_r.bmp", Robot.SIM_ACCURATE);
					if(list.size() > 0){
						CoordBean tmpCoordBean = list.get(0);
						//鼠标移动过去点击右键打开合成旗地图
						if(mouse.mouseRealMove(tmpCoordBean.getX(),tmpCoordBean.getY(),3,3,hwndrect) && mouse.mouseRightClick()){
							sleep.sleep(200);
							//矫正小地图的位置
							//
						}
					}*/
				}
			}else{
				System.out.println("窗口绑定失败");
			}
		}else{
			System.out.println("没有发现寻仙窗口");
		}

		//用完后一定要记得释放，释放内存，无论是否绑定了窗口、绑定是否成功，都可以直接调用此函数释放
		com.unbind();


		//飞去驿站
		//点击驿站老板
		//传送到国境
		//走路去地府
		//去找钟馗
		//领任务
		//开眼
		//获取任务坐标
		//飞往指定地点
		//自动寻路
		//进入战斗

	}
	
	/**
	 * 测试用
	 */
	public void imageSearchAndMouseRightClick(){
		//com = new Com();
		window = new Window(com.getActiveXComponent());
		String allWindowsStr = window.enumWindow(0,"记事本","",1);
		if(StringUtil.isNotEmpty(allWindowsStr)) {
			String[] windowarr = allWindowsStr.split(",");

			for (int i = 0; i < windowarr.length; i++) {
				String s = windowarr[i];
				int hwnd = Integer.valueOf(s);
				//获取窗口
				if(hwnd>0) {
					if (com.bind(hwnd, "normal", "normal", "normal", 0)) {
						window.setWindowActivate(hwnd);
                        Sleep sleep=new Sleep();
                        sleep.sleep(1000);
                        Press press=new Press(com.getActiveXComponent());	//创建模拟按键对象

						press.keyPress(Press.A);
						press.keyPress(Press.A);
						press.keyPress(Press.A);
						press.keyPress(Press.A);
					}
					com.unbind();
				}
			}
		}
        System.out.println();
	}

	//打开包裹
	public boolean openBag(Robot robot, Press press,int[] hwndrect){
		//先看有没有打开
		for(int m =0 ;m < 5; m++){
			CoordBean cobean = robot.imageSearchFirst(hwndrect,"qi.bmp");
			if(cobean != null){
				addLog("打開包裹成功"+cobean.getX()+"-"+cobean.getY());
				return true;
			}
		}
		//打开
		press.groupPress(Press.ALT,Press.E);
		//验证是否打开成功
		for(int m =0 ;m < 5; m++){
			CoordBean cobean = robot.imageSearchFirst(hwndrect,"qi.bmp");
			if(cobean != null){
				addLog("打開包裹成功"+cobean.getX()+"-"+cobean.getY());
				return true;
			}
		}
		addLog("打開包裹失敗");
		return false;
	}

	//打开任务栏
	public boolean openTask(Robot robot, Press press,int[] hwndrect){
		press.groupPress(Press.ALT,Press.Q);
		return true;
	}

	//打开小地图，返回小地图的位置
	public CoordBean openMap(Robot robot, Press press,int[] hwndrect){
		//先看有没有打开
		for(int m =0 ;m < 5; m++){
			CoordBean cobean = robot.imageSearchFirst(hwndrect,"s.bmp");
			if(cobean != null){
				addLog("打開小地图成功"+cobean.getX()+"-"+cobean.getY());
				return cobean;
			}
		}
		press.keyPress(Press.TAB);
		//验证是否打开成功
		for(int m =0 ;m < 5; m++){
			CoordBean cobean = robot.imageSearchFirst(hwndrect,"s.bmp");
			if(cobean != null){
				addLog("打開小地图成功"+cobean.getX()+"-"+cobean.getY());
				return cobean;
			}
		}
		return null;
	}

	/*飞旗子
	 * x y 目的地坐标
	 *city  1长安 2傲来 3长寿 4朱紫
	 * qz_h.bmp|qz_r.bmp|qz_l.bmp|qz_g.bmp|qz_b.bmp 黄红蓝绿白
	 */
	public boolean fly77(int x,int y,int city,int[] hwndrect,Mouse mouse,Sleep sleep){
		double realx = 0;
		double realy = 0;
		String searchImageName = "";

		if(city == 1){
			realx = x * 1.02;
			realy = y * 1.02;
			searchImageName = "qz_r.bmp";//
		}else if(city == 2){
			realx = x * 1.843;
			realy = y * 1.853;
			searchImageName = "qz_h.bmp";
		}else if(city == 3){
			realx = x * 1.327;
			realy = y * 1.324;
			searchImageName = "qz_g.bmp";
		}else if(city == 4){
			realx = x * 2.304;
			realy = y * 2.317;
			searchImageName = "qz_b.bmp";
		}
		int returnx = -1;
		int returny = -1;

		//找到对应颜色的合成棋
		List<CoordBean> list = robot.imageSearch(hwndrect[1], hwndrect[2], hwndrect[3], hwndrect[4], searchImageName, Robot.SIM_ACCURATE);
		if(list.size() > 0){
			CoordBean tmpCoordBean = list.get(0);
			//鼠标移动过去点击右键打开合成旗地图
			if(mouse.mouseRealMove(tmpCoordBean.getX(),tmpCoordBean.getY(),1,1,hwndrect) && mouse.mouseRightClick()){
				sleep.sleep(200);
				//判断是否成功打开
				for(int m =0 ;m < 5; m++){
					CoordBean cobean = robot.imageSearchFirst(hwndrect,"s.bmp");
					if(cobean != null){
						returnx = cobean.getX();
						returny = cobean.getY();
						for(int i =0 ;i < 5; i++){
							List<CoordBean> qzdList = robot.imageSearch(hwndrect[1], hwndrect[2], hwndrect[3], hwndrect[4],"qzd.bmp", Robot.SIM_ACCURATE);
							if(qzdList.size() > 0){
								realx = realx + returnx + 20;
								realy = returny - realy;
								CoordBean nearCoordBean = null;
								double l = 0;
								for (int j = 0; j < qzdList.size(); j++) {
									CoordBean t = qzdList.get(j);
									//找到最近的那个旗子点
									double _x = Math.abs((t.getX() - realx));
									double _y = Math.abs((t.getY() - realy));
									double _z = _x * _x + _y * _y;
									if(_z > l){
										l = _z;
										nearCoordBean = t;
									}
									//成功飞了过去
									if(mouse.mouseRealMove(nearCoordBean.getX(),nearCoordBean.getY(),1,1,hwndrect) && mouse.mouseLeftClick()){
										return true;
									}
								}
								break;
							}
						}
						break;
					}
				}
			}
		}

		return false;

	}

	//屏蔽人物和摊位
	public void hideAll(Press press){
		press.keyPress(Press.F9);
		press.groupPress(Press.ALT,Press.H);
	}

	//找到npc并点击
	public boolean findNpcAndClick(String city,String npcName,int[] hwndrect,Mouse mouse){
		//根据城市和npc名字获取图片，
		String searchImageName = getNpcImageUrlByCityAndName(city,npcName);
		if(findNowCity(hwndrect).equals(city)){
			//判断距离此npc的距离
			if(1==1){
				for(int m =0 ;m < 5; m++){
					CoordBean cobean = robot.imageSearchFirst(hwndrect,searchImageName);
					if(cobean != null){
						if(mouse.mouseRealMove(cobean.getX(),cobean.getY(),1,1,hwndrect) && mouse.mouseLeftClick()){
							return true;
						}
					}
				}
			}
		}
		return false;
    }

    //判断当前位置
    public String findNowCity(int[] hwndrect){
        String s = findStr.readStr(hwndrect[1], hwndrect[2], hwndrect[3], hwndrect[4],"9f2e3f-030303|2d3f2f-000000|3f9e4d-100000","",0.9,1);
	    return s;
    }

    //判断当前角色距离此npc的距离

	//飞飞行符
	//人物行走
	public boolean roleMove(int endx,int endy){
		return false;
	}
	//自动寻路
	public boolean autoMove(Robot robot, Press press,Mouse mouse,int[] hwndrect,int x,int y){
		CoordBean coordBean = openMap(robot,press,hwndrect);
		if(coordBean != null){
			//将鼠标移动到目的坐标对应小地图的坐标，按照不同的城市进行比例拉伸
			coordBean.setX(coordBean.getX() +x);
			coordBean.setY(coordBean.getY() +y);
			if(mouse.mouseRealMove(coordBean.getX(),coordBean.getY(),1,1,hwndrect) && mouse.mouseLeftClick()){
				return true;
			}

		}
		return false;
	}
	//等待人物移动完毕
	public void waitRoleMoving(int hwndrect[]){
		try {
			if(isRoleMoving(hwndrect)){
				Thread.sleep(500);
				waitRoleMoving(hwndrect);
			}
		}catch (Exception e){

		}
	}

	//判断人物是否在移动
	public boolean isRoleMoving(int hwndrect[]){
		//获取当前坐标，如果坐标发送变化，则说明在移动，否则就没有移动了
		try {
			//读取坐标1
			CoordBean cobean1 = robot.imageSearchFirst(hwndrect,"s.bmp");
			Thread.sleep(500);
			//读取坐标2
			CoordBean cobean2 = robot.imageSearchFirst(hwndrect,"s.bmp");
			if(cobean1.getX() == cobean2.getX() && cobean1.getY() == cobean2.getY()){
				return false;
			}else{
				return true;
			}
		}catch (Exception e){
			return false;
		}
	}

	//根据城市和npc名字获取图片地址，
	public String getNpcImageUrlByCityAndName(String city,String npcName){
		String url = "";
		if(city.equals("长安城")){
			if(npcName.equals("驿站老板")){
				url = "ca-yzlb.bmp";
			}
		}
		return url;
	}
	/**
	 * 日志纪录
	 * @param str
	 */
	public void addLog(String str){
		System.out.println(str);
		this.textArea.setText(str+"\n"+this.textArea.getText());
	}
}
